
--Menu class
Menu = {
	pWorld = nil,
	updateID = nil,
}

Menu.__index = Menu

function Menu:onEnter()
	Misc:log("Menu : onEnter .. " .. Misc:getNodeName(self))
	
	local function update()
        self:updateBox2D()
    end	
	self.updateID = CCScheduler:sharedScheduler():scheduleScriptFunc(update, 1/60.0, false)
end

function Menu:onExit()
	CCScheduler:sharedScheduler():unscheduleScriptEntry(self.updateID)
	if self.pWorld then
		self.pWorld:delete()
	end
end

function Menu:updateBox2D()
	local velocityIterations = 8;
	local positionIterations = 1;

	-- Instruct the world to perform a single step of simulation. It is
	-- generally best to keep the time step and iterations fixed.

	local pDelNodes = {};
	
	if self.pWorld then
	
		self.pWorld:Step(1/60.0, velocityIterations, positionIterations);
		--Iterate over the bodies in the physics world
		local b = self.pWorld:GetBodyList()
		while  b do
			local pUserData = b:GetUserData()
			if pUserData then
				--Synchronize the AtlasSprites position and rotation with the corresponding body
				local pNode = tolua.cast(pUserData, "CCMenuItemImage");
				pNode:setPosition( b:GetPosition().x * PTM_RATIO, b:GetPosition().y * PTM_RATIO );
				pNode:setRotation( -1 * CC_RADIANS_TO_DEGREES(b:GetAngle()) );

				local menuRect = getGlobalRect(self);
				local itemRect = getGlobalRect(pNode);
				if not CCRect:CCRectIntersectsRect(menuRect, itemRect) then
					if itemRect.origin.y <= menuRect.origin.y then
						pDelNodes[table.getn(pDelNodes)+1] = pNode;
					end
				end
			end
			b = b:GetNext()
		end
	end

	for i, v in ipairs(pDelNodes) do
		local body = tolua.cast(Misc:getUserData(v), "b2Body")
		if body then
			self.pWorld:DestroyBody(body)
		end
		v:removeFromParentAndCleanup(true);
	end
end

function Menu:menuWithCCMenu(ccMenu)
	local newMenu = {}
	setmetatable(newMenu, self)
	--self.__index = self
	
	tolua.setpeer(ccMenu, newMenu)

    self.pWorld = tolua.cast(Misc:getUserData(ccMenu), "b2World");
	local function onEnterOrExit(eventType)
		if eventType == kCCNodeOnExit then
			ccMenu:onExit()
		else
			ccMenu:onEnter()
		end
	end
	
	ccMenu:registerScriptHandler(onEnterOrExit)
	
	if ccMenu:getIsRunning() then
		ccMenu:onEnter()
	end
	return ccMenu
end
